﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using Card.Security;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Card.Web.Member
{
    public partial class UploadLogo : MemberBase
    {
        #region
        public string ImageID
        {
            get
            {
                return Request.QueryString["im"];
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {

            string fileName = string.Empty;
            string message = string.Empty;
            string width = string.Empty;
            string heigth = string.Empty;
            byte[] byt = this.fileUpload.FileBytes;

            if (byt == null || byt.Length <= 0)
            {
                this.MessageBox("请选择文件！");
                return;
            }

            string url = url = string.Format("{0}/ImageUpLoad.aspx?fileName={1}&t={2}",
                    Utility.ImageUtilty.ImageServer,
                    this.fileUpload.FileName,
                    CONST.UPLOAD_IMAGE_TYPE.USER_LOGO);

            WebRequest request = HttpWebRequest.Create(url);
            request.Method = "POST";
            request.Headers.Add("Cookie", string.Format("{0}={1}", CONST.CookieNames.Passport, CookieManager.GetCookie(CONST.CookieNames.Passport)));
            request.ContentLength = byt.Length;
            request.GetRequestStream().Write(byt, 0, byt.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (StreamReader dataStream = new StreamReader(response.GetResponseStream()))
            {
                var result = dataStream.ReadToEnd();
                JObject jResult = (JObject)JsonConvert.DeserializeObject(result);
                if (string.Compare(jResult.Property("result").Value.ToString(), CONST.YES_NO.YES, true) == 0)
                {
                    fileName = jResult.Property("fileName").Value.ToString();
                    width = jResult.Property("w").Value.ToString();
                    heigth = jResult.Property("h").Value.ToString();
                }
                else
                {
                    message = jResult.Property("message").Value.ToString();
                }
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                this.RegisterScript(string.Format("upload_sucess('{0}','{1}','{2}');", width, heigth, fileName), true);
            }
            else
            {
                this.MessageBox(string.Format("上传失败:'+unescape('{0}')+'", message));
            }
        }
    }
}
